package com.ruan.service;

import com.ruan.dao.GoodsMapper;
import com.ruan.dao.GoodsTypeMapper;
import com.ruan.entity.Goods;
import com.ruan.entity.Result;
import com.ruan.query.GoodsQuery;
import com.ruan.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @ClassName:GoodsService
 * @Author:阮昇
 * @Description:
 * @Datetime: 2023/7/1 18:25
 **/
@Service
public class GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    public Result addGoods(Goods goods) {
        Goods goods1 = goodsMapper.getGoodsByName(goods.getGoodsName());
        if(goods1!=null){
            return new Result(100,"该商品已存在");
        }
        Date now = new Date();
        String currentTime = String.format("%tF %<tT", now);
        goods.setGoodsReleaseTime(currentTime);
        int row = goodsMapper.addGoods(goods);
        if(row != 1){
            return new Result(100,"商品添加失败");
        }else {
            return new Result(200,"商品添加成功");
        }
    }

    public List<GoodsVo> getGoodsList(GoodsQuery goodsQuery) {
        List<GoodsVo> goodsVoList = goodsMapper.getGoodsList(goodsQuery);
        for (GoodsVo i:goodsVoList){
            i.setGoodsType(goodsTypeMapper.getGoodsTypeById(i.getGoodsTypeId()));
        }
        return goodsVoList;
    }

    public Result editGoods(Goods goods) {
        Goods goods1 = goodsMapper.getGoodsByName(goods.getGoodsName());
        if(goods1!=null&&!goods1.getId().equals(goods.getId())){
            return new Result(100,"该商品已存在");
        }
        int row = goodsMapper.editGoods(goods);
        if(row != 1){
            return new Result(100,"商品修改失败");
        }else {
            return new Result(200,"商品修改成功");
        }
    }

    public Result deleteGoods(Integer id) {
        Date now = new Date();
        String currentTime = String.format("%tF %<tT", now);
        int row = goodsMapper.deleteGoods(id,currentTime);
        if(row != 1){
            return new Result(100,"商品删除失败");
        }else {
            return new Result(200,"商品删除成功");
        }
    }

    public Result deleteGoodsByIds(Integer[] ids) {
        Date now = new Date();
        String currentTime = String.format("%tF %<tT", now);
        int row = goodsMapper.deleteGoodsByIds(ids,currentTime);
        if(row!=ids.length){
            return new Result(100,"商品删除失败");
        }else {
            return new Result(200,"商品删除成功");
        }
    }

    public GoodsVo getGoodsById(Integer id) {
        GoodsVo goodsVo = goodsMapper.getGoodsById(id);
        goodsVo.setGoodsType(goodsTypeMapper.getGoodsTypeById(goodsVo.getGoodsTypeId()));
        return goodsVo;
    }

    public void addSales(Integer id, Integer count) {
        goodsMapper.addSales(id,count);
    }
}
